package mobile

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	jsoniter "github.com/json-iterator/go"
	"net/url"
	"strconv"
	"strings"
	"tcsc/models"
	"tcsc/sword"
	"time"

	_ "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	_ "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
)

// "sword"
type Login struct {
	beego.Controller
}

func (c *Login) Get() {
	c.SetSession("smssend", "1")
	// user_agent := c.Ctx.Request.Header.Get("User-Agent")
	// iswx := strings.Index(user_agent, "MicroMessenger")
	// t := c.GetString("type")
	// if t != "check" {
	// 	if iswx != -1 {
	// 		// uri := c.Ctx.Request.Referer()
	// 		// if uri != "" {
	// 		// 	c.SetSession("url", uri)
	// 		// }
	// 		c.Ctx.Redirect(302, "/mobile/login_wechat_check")
	// 	}
	// }
	// if c.GetSession("wechatwait") != nil {
	// 	c.Ctx.Redirect(302, "/mobile/sign")
	// } else {
	c.Data["s_title"] = `登入`
	c.Data["s_url"] = c.Ctx.Request.Host + "/mobile/login"
	c.TplName = "wechat/index/login.html"
	// }
}

func (c *Login) Post() {
	shopId := ""
	currentcity := c.GetSession("city")
	city := c.GetString("city")
	if currentcity == nil {
		c.SetSession("city", city)
	}
	username := c.GetString("mobile")
	password := c.GetString("password")
	code := c.GetString("code")
	passwordmd5 := sword.ToMD5(password)
	style := c.GetString("style")
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()
	if style == "0" {
		if is := models.Query(`select id,password,city from mt_member where mobile='` + username + `' and status=1`); is != nil {
			passwordsql := fmt.Sprint(is[0]["password"])
			if passwordmd5 == passwordsql {
				c.Data["json"] = 1
				if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
					beego.Debug(err)
				}
				if currentcity == nil {
					if city == "" {
						if is[0]["city"] != nil && is[0]["city"] != "台州" {
							if cityCode := models.Query(`select code from mt_area where name like '?'`, is[0]["city"].(string)); cityCode != nil {
								if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
									shopId = fmt.Sprint(shop[0]["id"])
								}
							}
						}
					} else if city == "台州市" {
						shopId = ""
					} else {
						if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
							if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
								shopId = fmt.Sprint(shop[0]["id"])
							}
						}
					}
					c.SetSession("shopId", shopId)
				}
				c.SetSession("wechat", is[0]["id"])
			} else {
				c.Data["json"] = 0 //密码错误
			}
		} else {
			c.Data["json"] = 3 //用户名不存在
		}
	} else {
		if smsresult := models.Query(`select addtime from mt_smssend where type=0 and code='` + code + `' and mobile='` + username + `' order by addtime desc`); smsresult != nil {
			addtime := fmt.Sprint(smsresult[0]["addtime"])
			loc, _ := time.LoadLocation("Local")
			timer, _ := time.ParseInLocation(Tparse, addtime, loc)
			timen := time.Now().Local()
			timer.Add(15 * time.Minute)
			if timer.Before(timen) {
				if is := models.Query(`select id,city from mt_member where mobile='` + username + `' and status=1`); is == nil {
					c.Data["json"] = 2
				} else {
					if currentcity == nil {
						if city == "" {
							if is[0]["city"] != nil && is[0]["city"] != "台州" {
								if cityCode := models.Query(`select code from mt_area where name like '?'`, is[0]["city"].(string)); cityCode != nil {
									if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
										shopId = fmt.Sprint(shop[0]["id"])
									}
								}
							}
						} else if city == "台州市" {
							shopId = ""
						} else {
							if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
								if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
									shopId = fmt.Sprint(shop[0]["id"])
								}
							}
						}
						c.SetSession("shopId", shopId)
					}
					c.SetSession("wechat", is[0]["id"].(string))
					c.Data["json"] = 1
					if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
						beego.Debug(err)
					}
				}
			} else {
				c.Data["json"] = 2 //验证码
			}
		} else {
			c.Data["json"] = 2 //验证码错误
		}
	}

	c.ServeJSON()
}

type LoginApp struct {
	BaseController
}

func (c *LoginApp) Post() {
	username := c.GetString("mobile")
	password := c.GetString("password")
	code := c.GetString("code")
	var js = make(map[string]interface{})
	passwordmd5 := sword.ToMD5(password)
	style := c.GetString("style")
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()

	var status []int
	if style == "0" {
		if is := models.Query(`select id,password from mt_member where mobile='` + username + `' and status=1`); is != nil {
			passwordsql := fmt.Sprint(is[0]["password"])
			if passwordmd5 == passwordsql {
				js["status"] = 1
				js["uid"] = is[0]["id"]
				if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
					beego.Debug(err)
				}
				c.Data["json"] = js
			} else {
				status = append(status, 0)
				c.Data["json"] = status //密码错误
			}
		} else {
			status = append(status, 3)
			c.Data["json"] = status //用户名不存在
		}
	} else {
		if smsresult := models.Query(`select addtime from mt_smssend where type=0 and code='` + code + `' and mobile='` + username + `' order by addtime desc`); smsresult != nil {
			addtime := fmt.Sprint(smsresult[0]["addtime"])
			loc, _ := time.LoadLocation("Local")
			timer, _ := time.ParseInLocation(Tparse, addtime, loc)
			timen := time.Now().Local()
			timer.Add(15 * time.Minute)
			if timer.Before(timen) {
				if is := models.Query(`select id from mt_member where mobile='` + username + `' and status=1`); is == nil {
					status = append(status, 3)
					c.Data["json"] = status //用户名不存在
				} else {
					js["status"] = 1
					js["uid"] = is[0]["id"]
					if err := models.Exec(fmt.Sprintf(`update mt_member set logintime='%v',loginip='%v',loginnumber=loginnumber+1 where id=%v`, addtime, addr, is[0]["id"])); err != nil {
						beego.Debug(err)
					}
					c.Data["json"] = js
				}
			} else {
				status = append(status, 2)
				c.Data["json"] = status //验证码
			}
		} else {

			status = append(status, 2)
			c.Data["json"] = status //验证码
		}
	}
	// beego.Debug(js)
	// c.Data["json"] = js
	c.ServeJSON()
}

type SmsResp struct {
	Code      string //请求状态码
	Message   string //状态码的描述
	BizId     string //发送回执ID
	RequestId string //请求ID
}

type LoginSmssend struct {
	beego.Controller
}

func (c *LoginSmssend) Get() {
	if !(c.GetSession("smssend") == "1" || c.GetString("app") == sword.ToMD5("tongcaiApp2.0")) {
		c.Data["json"] = 1
		c.ServeJSON()
		return
	}
	ip := c.Ctx.Input.IP()
	// beego.Debug(ip)
	ip = strings.Split(ip, ":")[0]

	if refer := models.Query(`select id from mt_smsrefer where ip=?`, ip); refer != nil {
		c.StopRun()
		return
	}

	nows := time.Now().Local()
	nows2 := nows.Add(-60 * time.Second).Format(Tparse)
	if is := models.Query(`select id from mt_smssend where ip=? and addtime>?`, ip, nows2); is != nil {
		c.StopRun()
		return
	}

	nows3 := nows.Format("2006-01-02")
	if isn := models.Query(`select count(*) as num from mt_smssend where ip=? and addtime>?`, ip, nows3); isn != nil {
		nums, _ := strconv.Atoi(fmt.Sprint(isn[0]["num"]))
		if nums > 10 {
			models.Exec(`insert into mt_smsrefer (ip) values (?)`, ip)
			c.StopRun()
			return
		}
	}

	phoneNumbers := c.GetString("mobile")
	beego.Debug(c.GetString("mobile"))
	t := c.GetString("type")
	code := sword.RandomNum(6)
	var (
		//gatewayUrl      = "http://dysmsapi.aliyuncs.com/"
		accessKeyId     = "LTAIKwWr7N72mKT9"
		accessKeySecret = "7Ub2Rzmb7aWD9S6kWv3V8qXeWrFeGJ"
		signName        = "浙江统采网络科技有限公司"
		templateCode    = "SMS_133135035"
		templateParam   = "{\"code\":\"" + code + "\"}"
	)
	if t == "0" {
		if is := models.Query(`select id from mt_member where mobile='` + phoneNumbers + `' and status=1`); is != nil {
			client, _ := sdk.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessKeySecret)
			req := requests.NewCommonRequest()
			req.Method = "POST"
			req.Scheme = "http" // https | http
			req.Domain = "dysmsapi.aliyuncs.com"
			req.Version = "2017-05-25"
			req.ApiName = "SendSms"
			req.QueryParams["PhoneNumbers"] = phoneNumbers
			req.QueryParams["SignName"] = signName
			req.QueryParams["TemplateCode"] = templateCode
			req.QueryParams["TemplateParam"] = templateParam
			resp, err := client.ProcessCommonRequest(req)
			if err != nil {
				beego.Debug("ali ecs client failed, err:", err.Error())
				c.Data["json"] = 0
				c.ServeJSON()
				return
			}
			var smsResp SmsResp
			err = jsoniter.Unmarshal(resp.GetHttpContentBytes(), &smsResp)
			if err != nil {
				beego.Debug("unmarshal response params failed")
				c.Data["json"] = 0
				c.ServeJSON()
				return
			}
			if smsResp.Code != "OK" {
				//err = error().New("code:" + smsResp.Code + ".message:" + smsResp.Message)
				c.Data["json"] = 0
				c.ServeJSON()
				return
			}
			if err = models.Exec(`insert into mt_smssend (mobile,type,code,addtime,ip) values ('` + phoneNumbers + `','` + t + `','` + code + `','` + sword.Gettimes("") + `','` + ip + `')`); err == nil {
				c.Data["json"] = 1
			} else {
				c.Data["json"] = 0
			}
		} else {
			c.Data["json"] = 2
		}
	} else {
		templateCode = "SMS_133170279"
		client, _ := sdk.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessKeySecret)
		req := requests.NewCommonRequest()
		req.Method = "POST"
		req.Scheme = "http" // https | http
		req.Domain = "dysmsapi.aliyuncs.com"
		req.Version = "2017-05-25"
		req.ApiName = "SendSms"
		req.QueryParams["PhoneNumbers"] = phoneNumbers
		req.QueryParams["SignName"] = signName
		req.QueryParams["TemplateCode"] = templateCode
		req.QueryParams["TemplateParam"] = templateParam
		resp, err := client.ProcessCommonRequest(req)
		if err != nil {
			beego.Debug("ali ecs client failed, err:", err.Error())
			c.Data["json"] = 0
			c.ServeJSON()
			return
		}
		var smsResp SmsResp
		err = jsoniter.Unmarshal(resp.GetHttpContentBytes(), &smsResp)
		if err != nil {
			beego.Debug("unmarshal response params failed")
			c.Data["json"] = 0
			c.ServeJSON()
			return
		}
		if smsResp.Code != "OK" {
			//err = error().New("code:" + smsResp.Code + ".message:" + smsResp.Message)
			c.Data["json"] = 0
			c.ServeJSON()
			return
		}
		if err = models.Exec(`insert into mt_smssend (mobile,type,code,addtime,ip) values ('` + phoneNumbers + `','` + t + `','` + code + `','` + sword.Gettimes("") + `','` + ip + `')`); err == nil {
			c.Data["json"] = 1
		} else {
			c.Data["json"] = 0
		}
	}
	c.ServeJSON()
}

var (
	Wx_appid  = beego.AppConfig.String("wx_appid")
	Url       = beego.AppConfig.String("url")
	Wx_secret = beego.AppConfig.String("wx_secret")
)

type LoginWechatCheck struct {
	beego.Controller
}

func (c *LoginWechatCheck) Get() {
	uri := c.GetString("url")
	c.SetSession("login", "ok")
	var redirect_uri string
	if uri == "" {
		redirect_uri = url.QueryEscape(Url + "/mobile/login_wechat_check_oauth")
	} else {
		redirect_uri = url.QueryEscape(Url + "/mobile/login_wechat_check_oauth?url=" + uri)
	}

	c.Ctx.Redirect(302, "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Wx_appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect")
}

type LoginWechat struct {
	beego.Controller
}

func (c *LoginWechat) Get() {
	if c.GetSession("city") == nil {
		c.SetSession("logincity", c.GetString("city"))
	}
	c.SetSession("login", "value")
	tid := c.GetString("tid")
	if tid == "" {
		tid = "0"
	}
	uri := c.GetString("url")
	var redirect_uri string
	if uri == "" {
		redirect_uri = url.QueryEscape(Url + "/mobile/login_wechat_oauth")
	} else {
		redirect_uri = url.QueryEscape(Url + "/mobile/login_wechat_oauth?url=" + uri)

	}
	c.Ctx.Redirect(302, "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Wx_appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect")
}

type Token struct {
	Access_token  string `json:"access_token"`
	Expires_in    int    `json:"expires_in"`
	Refresh_token string `json:"refresh_token"`
	Openid        string `json:"openid"`
	Scope         string `json:"scope"`
	Errcode       string `json:"errcode"`
	Errmsg        string `json:"errmsg"`
}

type UserInfo struct {
	Openid     string        `json:"openid"`
	Nickname   string        `json:"nickname"`
	Sex        int           `json:"sex"`
	Province   string        `json:"province"`
	City       string        `json:"city"`
	Country    string        `json:"country"`
	Headimgurl string        `json:"headimgurl"`
	Privilege  []interface{} `json:"privilege"`
	Unionid    string        `json:"unionid"`
	Errcode    string        `json:"errcode"`
	Errmsg     string        `json:"errmsg"`
}

type LoginWechatOauth struct {
	beego.Controller
}

func (c *LoginWechatOauth) Get() {

	code := c.Input().Get("code")

	token_url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Wx_appid + "&secret=" + Wx_secret + "&code=" + code + "&grant_type=authorization_code"
	req1 := httplib.Get(token_url)
	m1 := new(Token)
	req1.ToJSON(&m1)
	if m1.Errcode != "" {
		beego.Debug(m1.Errcode)
		c.StopRun()
	}
	access_token_url := "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Wx_appid + "&grant_type=refresh_token&refresh_token=" + m1.Refresh_token
	req2 := httplib.Get(access_token_url)
	m2 := new(Token)
	req2.ToJSON(&m2)
	if m2.Errcode != "" {
		beego.Debug(m2.Errcode)
		c.StopRun()
	}
	user_info_url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + m2.Access_token + "&openid=" + m2.Openid + "&lang=zh_CN"
	req3 := httplib.Get(user_info_url)
	m3 := new(UserInfo)
	req3.ToJSON(&m3)
	// str3, _ := req3.String()
	if m3.Errcode != "" {
		beego.Debug(m3.Errcode)
		c.StopRun()
	}
	member := models.Query("select id,mobile,city from mt_member where wx_unionid='" + m3.Unionid + "' and status=1 limit 1")
	// utils.Display("mem", m3)
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()
	if member == nil {
		we := models.Query(`select id from mt_member_wechat where wx_unionid=?`, m3.Unionid)
		if we != nil {
			c.SetSession("wechatwait", fmt.Sprint(we[0]["id"]))
			c.Ctx.Redirect(302, "/mobile/sign")
		} else {
			var avatar int64
			if len(m3.Headimgurl) > 3 {
				req4 := httplib.Get(m3.Headimgurl)
				if err := req4.ToFile(`static/avatar/` + m3.Unionid + `.jpg`); err != nil {
					beego.Debug(err)
				} else {
					var resources models.Mt_resources
					resources.Addtime = sword.Timeget()
					resources.Ip = addr
					resources.Name = m3.Unionid + `.jpg`
					resources.Path = `/static/avatar/`
					resources.Pathname = `/static/avatar/` + m3.Unionid + `.jpg`
					resources.Type = 0
					if avatar, err = models.Orm().Insert(&resources); err != nil {
						beego.Debug(err)
					}
				}
			}
			m3.Nickname = sword.FilterEmoji(m3.Nickname)
			var shareuid string
			if c.GetSession("share_uid") == nil {
				shareuid = "0"
			} else {
				shareuid = c.GetSession("share_uid").(string)
				if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
					if fmt.Sprint(t[0]["type"]) == "0" {
						shareuid = "0"
					}
				}
			}
			var sid = "0"
			if pro := models.Query(`select code from mt_area where name like '%` + m3.Province + `%'`); pro != nil {
				scode := fmt.Sprint(pro[0]["code"])
				if smem := models.Query(`select id from mt_member where service=1 and servicearea like '%,` + scode + `,%'`); smem != nil {
					sid = smem[0]["id"].(string)
				}
			}
			sql := fmt.Sprintf(`insert into mt_member_wechat(uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_gzh,country,province,city,sid) values(
				'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, avatar, m3.Nickname, m3.Sex, addtime, addr, addtime, addr,
				m3.Unionid, m3.Openid, m3.Country, m3.Province, m3.City, sid)
			if res, err := models.Orm().Raw(sql).Exec(); err != nil {
				beego.Debug(err)
			} else {
				if uidi, err := res.LastInsertId(); err != nil {
					beego.Debug(err)
				} else {
					c.SetSession("wechatwait", fmt.Sprint(uidi))
					c.Ctx.Redirect(302, "/mobile/sign")
				}
			}
		}
	} else {
		// shopId := ""
		// city := ""
		currentcity := c.GetSession("city")
		models.Exec("update mt_member set logintime='" + addtime + "',loginip='" + addr + "',loginnumber=loginnumber+1,wx_openid_gzh='" + m3.Openid + "' where wx_unionid='" + m3.Unionid + "'")
		if currentcity == nil {
			// if c.GetSession("logincity") != nil {
			// 	city = fmt.Sprint(c.GetSession("logincity"))
			// 	c.DelSession("logincity")
			// 	c.SetSession("city", city)
			// }
			// if city == "" {
			// 	if member[0]["city"] != nil && member[0]["city"] != "台州" {
			// 		if cityCode := models.Query(`select code from mt_area where name like '%?%'`, member[0]["city"].(string)); cityCode != nil {
			// 			if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
			// 				shopId = fmt.Sprint(shop[0]["id"])
			// 			}
			// 		}
			// 	}
			// } else if city != "台州市" {
			// 	if cityCode := models.Query(`select code from mt_area where name = ?`, city); cityCode != nil {
			// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
			// 			shopId = fmt.Sprint(shop[0]["id"])
			// 		}
			// 	}
			// }
			// c.SetSession("shopId", shopId)
		}
		c.SetSession("wechat", member[0]["id"])
		urlre := c.GetString("url")
		if urlre != "" {
			c.Ctx.Redirect(302, urlre)
		} else {
			c.Ctx.Redirect(302, "/mobile/my")
		}
	}
}

type LoginWechatCheckOauth struct {
	beego.Controller
}

func (c *LoginWechatCheckOauth) Get() {
	uri := c.GetString("url")
	c.SetSession("login", "value")
	code := c.Input().Get("code")
	token_url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Wx_appid + "&secret=" + Wx_secret + "&code=" + code + "&grant_type=authorization_code"
	req1 := httplib.Get(token_url)
	m1 := new(Token)
	req1.ToJSON(&m1)
	if m1.Errcode != "" {
		beego.Debug(m1.Errcode)
		c.StopRun()
	}
	access_token_url := "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Wx_appid + "&grant_type=refresh_token&refresh_token=" + m1.Refresh_token
	req2 := httplib.Get(access_token_url)
	m2 := new(Token)
	req2.ToJSON(&m2)
	if m2.Errcode != "" {
		beego.Debug(m2.Errcode)
		c.StopRun()
	}
	user_info_url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + m2.Access_token + "&openid=" + m2.Openid + "&lang=zh_CN"
	req3 := httplib.Get(user_info_url)
	m3 := new(UserInfo)
	req3.ToJSON(&m3)
	// str3, _ := req3.String()
	if m3.Errcode != "" {
		beego.Debug(m3.Errcode)
		c.StopRun()
	}
	member := models.Query("select id,mobile,city from mt_member where wx_unionid='" + m3.Unionid + "' and status=1 limit 1")
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()
	if member == nil {
		// c.Ctx.Redirect(302, "/mobile/login?type=check")
		// if c.GetSession("login") == nil {
		we := models.Query(`select id from mt_member_wechat where wx_unionid=?`, m3.Unionid)
		if we != nil {
			c.SetSession("wechatwait", fmt.Sprint(we[0]["id"]))
			c.Ctx.Redirect(302, "/mobile/index")
			// urlre := c.GetString("url")
			// if urlre != "" {
			// 	c.Ctx.Redirect(302, urlre)
			// } else {
			// }
		} else {
			var avatar int64
			if len(m3.Headimgurl) > 3 {
				req4 := httplib.Get(m3.Headimgurl)
				if err := req4.ToFile(`static/avatar/` + m3.Unionid + `.jpg`); err != nil {
					beego.Debug(err)
				} else {
					var resources models.Mt_resources
					resources.Addtime = sword.Timeget()
					resources.Ip = addr
					resources.Name = m3.Unionid + `.jpg`
					resources.Path = `/static/avatar/`
					resources.Pathname = `/static/avatar/` + m3.Unionid + `.jpg`
					resources.Type = 0
					if avatar, err = models.Orm().Insert(&resources); err != nil {
						beego.Debug(err)
					}
				}
			}
			m3.Nickname = sword.FilterEmoji(m3.Nickname)
			var shareuid string
			if c.GetSession("share_uid") == nil {
				shareuid = "0"
			} else {
				shareuid = c.GetSession("share_uid").(string)
				if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
					if fmt.Sprint(t[0]["type"]) == "0" {
						shareuid = "0"
					}
				}
			}
			var sid = "0"
			if pro := models.Query(`select code from mt_area where name like '%` + m3.Province + `%'`); pro != nil {
				scode := fmt.Sprint(pro[0]["code"])
				if smem := models.Query(`select id from mt_member where service=1 and servicearea like '%,` + scode + `,%'`); smem != nil {
					sid = smem[0]["id"].(string)
				}
			}
			sql := fmt.Sprintf(`insert into mt_member_wechat(uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_gzh,country,province,city,sid) values(
				'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, avatar, m3.Nickname, m3.Sex, addtime, addr, addtime, addr,
				m3.Unionid, m3.Openid, m3.Country, m3.Province, m3.City, sid)
			if res, err := models.Orm().Raw(sql).Exec(); err != nil {
				beego.Debug(err)
			} else {
				if uidi, err := res.LastInsertId(); err != nil {
					beego.Debug(err)
				} else {
					c.SetSession("wechatwait", fmt.Sprint(uidi))

					if uri != "" {

						c.Ctx.Redirect(302, uri)
					} else {

						c.Ctx.Redirect(302, "/mobile/index")
					}
					// urlre := c.GetString("url")
					// if urlre != "" {
					// 	c.Ctx.Redirect(302, urlre)
					// } else {
					// }
				}
			}
		}

		// } else {
		// 	c.Ctx.Redirect(302, "/mobile/login?type=check")
		// }
	} else {
		models.Exec("update mt_member set logintime='" + addtime + "',loginip='" + addr + "',loginnumber=loginnumber+1,wx_openid_gzh='" + m3.Openid + "' where wx_unionid='" + m3.Unionid + "'")
		if mobile := fmt.Sprint(member[0]["mobile"]); mobile == "" {
			c.SetSession("wechatwait", fmt.Sprint(member[0]["id"]))
			c.Ctx.Redirect(302, "/mobile/sign")
		} else {
			// shopId := ""
			currentcity := c.GetSession("city")
			if currentcity == nil {
				// c.SetSession("city", member[0]["city"])
				// if member[0]["city"] != nil && member[0]["city"] != "台州" {
				// 	if cityCode := models.Query(`select code from mt_area where name like '%?%'`, member[0]["city"].(string)); cityCode != nil {
				// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ?`, cityCode[0]["code"]); shop != nil {
				// 			shopId = fmt.Sprint(shop[0]["id"])
				// 		}
				// 	}
				// }
				// c.SetSession("shopId", shopId)
			}
			c.SetSession("wechat", member[0]["id"])
			if uri != "" {
				c.Ctx.Redirect(302, uri)
			} else {
				c.Ctx.Redirect(302, "/mobile/index")
			}
		}
	}
}

type Sign struct {
	beego.Controller
}

func (c *Sign) Get() {
	c.Data["s_url"] = c.Ctx.Request.Host + c.Ctx.Request.RequestURI
	if c.GetSession("wechatwait") != nil {
		c.Data["s_title"] = `验证手机`
	} else {
		c.Data["s_title"] = `注册`
	}
	c.TplName = "wechat/index/sign.html"
}
func (c *Sign) Post() {
	defer c.ServeJSON()

	wechatwait := c.GetSession("wechatwait")
	var id string
	if wechatwait != nil {
		id = wechatwait.(string)
	}
	if id == "" {
		id = c.GetString("wid")
	}
	mobile := c.GetString("mobile")
	password := c.GetString("password")
	code := c.GetString("code")

	if smsresult := models.Query(`select addtime from mt_smssend where type=1 and code='` + code + `' and mobile='` + mobile + `' order by addtime desc`); smsresult != nil {
		addtime := fmt.Sprint(smsresult[0]["addtime"])
		loc, _ := time.LoadLocation("Local")
		timer, _ := time.ParseInLocation(Tparse, addtime, loc)
		timen := time.Now().Local()
		timer = timer.Add(15 * time.Minute)
		if timer.After(timen) {
			if id == "" {
				var shareuid string
				if c.GetSession("share_uid") == nil {
					shareuid = "0"
				} else {
					shareuid = c.GetSession("share_uid").(string)
					if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
						if fmt.Sprint(t[0]["type"]) == "0" {
							shareuid = "0"
						}
					}
				}
				if is := models.Query(`select id from mt_member where mobile='` + mobile + `' and status=1`); is != nil {
					c.Data["json"] = 2 //已注册
				} else {
					addtime := sword.Gettimes("")
					addr := c.Ctx.Input.IP()
					now := time.Now()
					monicker := fmt.Sprintf(`TCSC%v%v%v%v`, now.Year(), int(now.Month()), now.Day(), sword.RandStr(2))
					sql := fmt.Sprintf(`insert into mt_member(uid,monicker,mobile,addtime,addip,logintime,loginip,password) values(
				'%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, monicker, mobile, addtime, addr, addtime, addr, sword.ToMD5(password))
					if res, err := models.Orm().Raw(sql).Exec(); err != nil {
						beego.Debug(err)
						c.Data["json"] = 0
					} else {
						if uidi, err := res.LastInsertId(); err != nil {
							beego.Debug(err)
							c.Data["json"] = 0
						} else {
							c.SetSession("wechat", fmt.Sprint(uidi))
							c.Data["json"] = 1
						}
					}
				}
			} else {
				if is := models.Query(`select id,wx_unionid,password from mt_member where mobile='` + mobile + `' and status=1`); is != nil {
					if fmt.Sprint(is[0]["password"]) != sword.ToMD5(password) {
						c.Data["json"] = 4
						return
					}
					if wx_unionid := fmt.Sprint(is[0]["wx_unionid"]); wx_unionid != "" && wx_unionid != "<nil>" {
						c.Data["json"] = 2
					} else {
						mw := models.Query(`select * from mt_member_wechat where id=` + id)[0]
						if err := models.Query(fmt.Sprintf(`update mt_member set monicker='%v',avatar=%v,sex=%v,logintime='%v',loginip='%v',
						wx_unionid='%v',wx_openid_xapp='%v',wx_openid_gzh='%v',country='%v',province='%v',city='%v',sid='%v'
						 where id=%v`, mw["monicker"], mw["avatar"], mw["sex"], mw["logintime"], mw["loginip"], mw["wx_unionid"],
							mw["wx_openid_xapp"], mw["wx_openid_gzh"], mw["country"], mw["province"], mw["city"], mw["sid"],
							is[0]["id"])); err != nil {
							beego.Debug(err)
							c.Data["json"] = 0
						} else {
							c.SetSession("wechat", fmt.Sprint(is[0]["id"]))
							c.Data["json"] = 1
						}
					}
				} else {
					mw := models.Query(`select * from mt_member_wechat where id=` + id)[0]
					o := models.Orm()
					if res, err := o.Raw(fmt.Sprintf(`insert into mt_member 
						(uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_xapp,
							wx_openid_gzh,country,province,city,sid,password,mobile) 
						values('%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`,
						mw["uid"], mw["avatar"], mw["monicker"], mw["sex"], mw["addtime"], mw["addip"], mw["logintime"],
						mw["loginip"], mw["wx_unionid"], mw["wx_openid_xapp"], mw["wx_openid_gzh"], mw["country"],
						mw["province"], mw["city"], mw["sid"], sword.ToMD5(password), mobile)).Exec(); err != nil {
						c.Data["json"] = 0
						beego.Debug(err)
					} else {
						rid, _ := res.LastInsertId()
						c.SetSession("wechat", fmt.Sprint(rid))
						c.Data["json"] = 1
					}
				}
			}
		} else {
			c.Data["json"] = 3 //验证码过期
		}
	} else {
		c.Data["json"] = 3 //验证码错误
	}
}

type Logout struct {
	beego.Controller
}

func (c *Logout) Get() {
	c.DelSession("wechat")
	c.Ctx.Redirect(302, "/mobile/login")
}

type LoginXapp struct {
	BaseController
}

func (c *LoginXapp) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	encryptedData := c.GetString("encryptedData")
	code := c.GetString("code")
	iv := c.GetString("iv")
	userinfo, err := models.XappLogin(code, encryptedData, iv)
	if err != nil {
		beego.Debug(err)
		js["status"] = 0
		return
	}
	//beego.Debug(userinfo.UnionID)
	//beego.Debug(userinfo.Openid)
	member := models.Query(`select id,mobile from mt_member where wx_unionid='` + userinfo.UnionID + `' and status=1 limit 1`)
	// utils.Display("userinfo", userinfo)
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()
	if member == nil {
		var avatar int64
		if len(userinfo.AvatarURL) > 3 {
			req4 := httplib.Get(userinfo.AvatarURL)
			if err := req4.ToFile(`static/avatar/` + userinfo.UnionID + `.jpg`); err != nil {
				beego.Debug(err)
			} else {
				var resources models.Mt_resources
				resources.Addtime = sword.Timeget()
				resources.Ip = addr
				resources.Name = userinfo.UnionID + `.jpg`
				resources.Path = `/static/avatar/`
				resources.Pathname = `/static/avatar/` + userinfo.UnionID + `.jpg`
				resources.Type = 0
				if avatar, err = models.Orm().Insert(&resources); err != nil {
					beego.Debug(err)
				}
			}
		}
		userinfo.NickName = sword.FilterEmoji(userinfo.NickName)
		var shareuid string
		if c.GetSession("share_uid") == nil {
			shareuid = "0"
		} else {
			shareuid = c.GetSession("share_uid").(string)
			if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
				if fmt.Sprint(t[0]["type"]) == "0" {
					shareuid = "0"
				}
			}
		}
		var sid = "0"
		if pro := models.Query(`select code from mt_area where name like '%` + userinfo.Province + `%'`); pro != nil {
			scode := fmt.Sprint(pro[0]["code"])
			if smem := models.Query(`select id from mt_member where service=1 and servicearea like '%,` + scode + `,%'`); smem != nil {
				sid = smem[0]["id"].(string)
			}
		}
		sql := fmt.Sprintf(`insert into mt_member_wechat (uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_xapp,country,province,city,sid) values(
				'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, avatar, userinfo.NickName, userinfo.Gender, addtime, addr, addtime, addr,
			userinfo.UnionID, userinfo.Openid, userinfo.Country, userinfo.Province, userinfo.City, sid)
		if res, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
		} else {
			if uidi, err := res.LastInsertId(); err != nil {
				beego.Debug(err)
				js["status"] = 0
			} else {
				js["wid"] = uidi //前往绑定手机号码
				js["status"] = 2 //前往绑定手机号码
			}
		}
	} else {
		models.Exec("update mt_member set logintime='" + addtime + "',loginip='" + addr + "',loginnumber=loginnumber+1,wx_openid_xapp='" + userinfo.Openid + "' where wx_unionid='" + userinfo.UnionID + "'")
		c.SetSession("wechat", fmt.Sprint(member[0]["id"]))
		js["status"] = 1
	}
}

type LoginAppWechat struct {
	BaseController
}

func (c *LoginAppWechat) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js

	var userinfo = new(UserInfo)
	userinfo.City = c.Input().Get("city")
	userinfo.Openid = c.Input().Get("openid")
	userinfo.Nickname = c.Input().Get("nickname")
	userinfo.Sex, _ = c.GetInt("sex")
	userinfo.Headimgurl = c.Input().Get("headimgurl")
	userinfo.Province = c.Input().Get("province")
	userinfo.Unionid = c.Input().Get("unionid")
	member := models.Query(`select id,mobile from mt_member where wx_unionid='` + userinfo.Unionid + `' and status=1 limit 1`)
	// utils.Display("userinfo", userinfo)
	addtime := sword.Gettimes("")
	addr := c.Ctx.Input.IP()
	if member == nil {
		var avatar int64
		if len(userinfo.Headimgurl) > 3 {
			req4 := httplib.Get(userinfo.Headimgurl)
			if err := req4.ToFile(`static/avatar/` + userinfo.Unionid + `.jpg`); err != nil {
				beego.Debug(err)
			} else {
				var resources models.Mt_resources
				resources.Addtime = sword.Timeget()
				resources.Ip = addr
				resources.Name = userinfo.Unionid + `.jpg`
				resources.Path = `/static/avatar/`
				resources.Pathname = `/static/avatar/` + userinfo.Unionid + `.jpg`
				resources.Type = 0
				if avatar, err = models.Orm().Insert(&resources); err != nil {
					beego.Debug(err)
				}
			}
		}
		userinfo.Nickname = sword.FilterEmoji(userinfo.Nickname)
		var shareuid string
		if c.GetSession("share_uid") == nil {
			shareuid = "0"
		} else {
			shareuid = c.GetSession("share_uid").(string)
			if t := models.Query(`select type from mt_member where id=` + shareuid); t != nil {
				if fmt.Sprint(t[0]["type"]) == "0" {
					shareuid = "0"
				}
			}
		}
		var sid = "0"
		if pro := models.Query(`select code from mt_area where name like '%` + userinfo.Province + `%'`); pro != nil {
			scode := fmt.Sprint(pro[0]["code"])
			if smem := models.Query(`select id from mt_member where service=1 and servicearea like '%,` + scode + `,%'`); smem != nil {
				sid = smem[0]["id"].(string)
			}
		}
		sql := fmt.Sprintf(`insert into mt_member_wechat (uid,avatar,monicker,sex,addtime,addip,logintime,loginip,wx_unionid,wx_openid_app,country,province,city,sid) values(
				'%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v','%v')`, shareuid, avatar, userinfo.Nickname, userinfo.Sex, addtime, addr, addtime, addr,
			userinfo.Unionid, userinfo.Openid, userinfo.Country, userinfo.Province, userinfo.City, sid)
		if res, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
			js["status"] = 0
			return
		} else {
			if uidi, err := res.LastInsertId(); err != nil {
				beego.Debug(err)
				js["status"] = 0
			} else {
				js["wid"] = uidi //前往绑定手机号码
				js["status"] = 2 //前往绑定手机号码
			}
		}
	} else {
		models.Exec("update mt_member set logintime='" + addtime + "',loginip='" + addr + "',loginnumber=loginnumber+1,wx_openid_app='" + userinfo.Openid + "' where wx_unionid='" + userinfo.Unionid + "'")
		js["status"] = 1
		js["uid"] = member[0]["id"]
	}
}

type LoginXappCheck struct {
	BaseController
}

func (c *LoginXappCheck) Get() {
	var js = make(map[string]interface{})
	js["system"] = models.Systems()
	sess := c.GetSession("wechat")
	if sess == nil {
		js["status"] = 0
	} else {
		js["status"] = 1
	}
	c.Data["json"] = js
	c.ServeJSON()
}

type BindXapp struct {
	BaseController
}

func (c *BindXapp) Post() {
	defer c.ServeJSON()
	encryptedData := c.GetString("encryptedData")
	code := c.GetString("code")
	iv := c.GetString("iv")
	userinfo, err := models.XappLogin(code, encryptedData, iv)
	if err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	}
	if err := models.Exec(`update mt_member set wx_openid_xapp='` + userinfo.Openid + `' where id=` + c.Uid); err != nil {
		c.Data["json"] = 1
		beego.Debug(err)
	} else {
		c.Data["json"] = 0
	}
}

type LoginCheck struct {
	BaseController
}

func (c *LoginCheck) Post() {
	defer c.ServeJSON()
	c.Data["json"] = map[string]interface{}{"status": 0}
}

type CancelAccount struct {
	BaseController
}

func (c *CancelAccount) Get() {
	var js = make(map[string]interface{})
	passwordV := c.GetString("passwordV")
	if member := models.Query(`select * from mt_member where id=` + c.Uid + ` and password='` + sword.ToMD5(passwordV) + `'`); member != nil {
		if err := models.Exec(`update mt_member set status=0 where id=` + c.Uid); err != nil {
			js["status"] = 0
		} else {
			js["status"] = 1
		}
	} else {
		js["status"] = 2
	}
	c.Data["json"] = js
	c.ServeJSON()
}
